$(document).ready(function () {
    $('#pp').portal({ //主面板
        border: false,
        fit: true
    });
    getUserMenu();//easyUI
    treeSearch("ss", "menutree"); // 绑定树搜索功能
    getNowTime();//加载显示时间
    window.setInterval(getNowTime, 1000);//加载时间
    // checkLogin();//检查是否第一次登陆
    initData();
    //getChart();//加载统计图
    // getChart2();
    //getChart3();
})

//easyUI树
function getUserMenu() {
    $.messager.progress({text: '正在处理中...',});
    $.ajax({
            type: "post",
            url: system + "/main/getUserMenu",
            dataType: "json",
            success: function (data) {
                $.messager.progress('close');
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                $('#menutree').tree({
                    cascadeCheck: false,
                    checkbox: false,
                    lines: false,
                    data: data.data,
                    onClick: function (node) {//点击触发查询
                        if (isNull(node) || isNull(node.url)) {
                            return;
                        }
                        addTab(node.text, node.url, node.id, node.icon);
                    }
                })
                // addMenu(data.data);
            }, error: function (data) {
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}


//菜单信息的html拼接
function addMenu(listMenu) {
    if (listMenu != null && listMenu.length > 0) {
        var html = "<div class='easyui-accordion' data-options='border:false,fit:true'>";
        for (var i in listMenu) {
            html += "<div title=" + listMenu[i].text + " iconCls='" + listMenu[i].iconCls + "' style='padding:5px;'>" +
                "<ul id='menutree' class='easyui-tree' data-options='lines: false'>";
            var submenu = listMenu[i].children;
            for (var k in submenu) {
                if ("2" == submenu[k].menuTypeId) {
                    continue;
                }
                if (2 == submenu[k].menuLevel) {
                    var submenu2 = submenu[k].children;
                    html += "<li  iconCls=" + submenu[k].iconCls + " data-options=" + "state:'closed'" + "> <span>" + submenu[k].text + "</span><ul> ";
                    for (var m in submenu2) {
                        html += " <li iconCls= 'tree-folder " + submenu2[m].iconCls + "'><a iconCls='" + submenu2[m].iconCls + "' onclick='addMenuClick(this)' id=menu_" + submenu2[m].id + " href='javascript:void(0)'" +
                            " data-link=" + submenu2[m].url + ">" + submenu2[m].text + "</a></li>"
                    }
                    html += "</ul></li>";
                } else if (3 == submenu[k].menuLevel) {
                    html += " <li iconCls='tree-folder " + submenu[k].iconCls + "'><a iconCls='" + submenu[k].iconCls + "' onclick='addMenuClick(this)' id=menu_" + submenu[k].id + " href='javascript:void(0)'" +
                        " data-link=" + submenu[k].url + ">" + submenu[k].text + "</a></li>"
                }
            }
            html += "</ul></div>";
        }
        html += "</div>";
    }
    $(".wu-sidebar").append(html);
    $.parser.parse();//重新渲染页面，解决样式不生效
    //$(".easyui-accordion").accordion('getSelected').panel('collapse'); //关闭第一个弹开
}

function addMenuClick(obj) {//右侧的菜单点击事件
    var title = $(obj).text();
    var url = $(obj).attr('data-link');
    var icon = $(obj).attr("iconCls");
    var id = $(obj).attr('id');
    addTab(title, url, id, icon);
}

// 增加标签页，有该选项卡则刷新，无则新增选项卡
function addTab(title, url, id, icon) {
    var content = createFrame(url, id);
    if ($('#wu-tabs').tabs('exists', title)) {
        $('#wu-tabs').tabs('select', title); // 选中并刷新
        var currTab = $('#wu-tabs').tabs('getSelected');
        var url = $(currTab.panel('options').content).attr('src');
        if (url != undefined && currTab.panel('options').title != 'About') {
            $('#wu-tabs').tabs('update', {
                tab: currTab,
                options: {
                    id: id,
                    content: content,
                    icon: icon
                }
            })
        }
    } else {
        $('#wu-tabs').tabs('add', {
            id: id,
            title: title,
            content: content,
            closable: true,
            icon: icon,
            tools: [{
                iconCls: 'icon-mini-refresh',
                handler: function () {
                    var currTab = $('#wu-tabs').tabs('getSelected');
                    $('#wu-tabs').tabs('update', {
                        tab: currTab,
                        options: {
                            content: createFrame(url, id)
                        }
                    })
                }
            }]
        });
    }
    $('.tab-iframe').parent().css({
        overflow: 'hidden'
    });
    tabClose();
    $('.icon-mini-refresh,.tabs-close').removeAttr('href');
    return content;
}

// 选项卡需要的iframe标签
function createFrame(url, id) {
    var s = '<iframe id="f' + id + '" class="tab-iframe" scrolling="auto" frameborder="0" src="' + url
        + '" style="\width:100%;height:100%;"></iframe>';
    return s;
}


function tabClose() {
    /*双击关闭TAB选项卡*/
    $(".tabs-inner").dblclick(function () {
        var subtitle = $(this).children(".tabs-closable").text();
        $('#wu-tabs').tabs('close', subtitle);
    })
    /*为选项卡绑定右键*/
    $(".tabs-inner").bind('contextmenu', function (e) {
        var subtitle = $(this).children(".tabs-closable").text();
        if (null != subtitle && "" != subtitle && undefined != subtitle) {//取消首页的右键功能
            $('#mm').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
            $('#mm').data("currtab", subtitle);
            $('#wu-tabs').tabs('select', subtitle);
            return false;
        }
    });
    tabCloseEven();
}

//绑定右键菜单事件
function tabCloseEven() {
    //刷新
    $('#mm-tabupdate').click(function () {
        var currTab = $('#wu-tabs').tabs('getSelected');
        var url = $(currTab.panel('options').content).attr('src');
        $('#wu-tabs').tabs('update', {
            tab: currTab,
            options: {
                content: createFrame(url)
            }
        })
    })
    //关闭当前
    $('#mm-tabclose').click(function () {
        var currtab_title = $('#mm').data("currtab");
        $('#wu-tabs').tabs('close', currtab_title);
    })
    //全部关闭
    $('#mm-tabcloseall').click(function () {
        $('.tabs-inner span').each(function (i, n) {
            var t = $(n).text();
            if ("首页" != t) {
                $('#wu-tabs').tabs('close', t);
            }
        });
    });

    // 关闭除当前之外的TAB
    $('#mm-tabcloseother').click(function () {
        var currtab_title = $('#mm').data("currtab");
        $('.tabs-inner span').each(function (i, n) {
            var t = $(n).text();
            if (t != currtab_title && "首页" != t)
                $('#wu-tabs').tabs('close', t);
        });
    });
    // 关闭当前右侧的TAB
    $('#mm-tabcloseright').click(function () {
        var nextall = $('.tabs-selected').nextAll();
        if (nextall.length == 0) {
            //$.messager.alert('系统提示', '后边没有啦~~', 'error');
            return false;
        }
        nextall.each(function (i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            if ("首页" != t) {
                $('#wu-tabs').tabs('close', t);
            }
        });
        return false;
    });
    // 关闭当前左侧的TAB
    $('#mm-tabcloseleft').click(function () {
        var prevall = $('.tabs-selected').prevAll();
        if (prevall.length == 0) {
            // $.messager.alert('系统提示', '到头了，前边没有啦~~', 'error');
            return false;
        }
        prevall.each(function (i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            if ("首页" != t) {
                $('#wu-tabs').tabs('close', t);
            }
        });
        return false;
    });

    //退出
    $("#mm-exit").click(function () {
        $('#mm').menu('hide');
    })

}


//获取当前时间
function getNowTime() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    var h = date.getHours();
    var i = date.getMinutes();
    var s = date.getSeconds();
    $("#sysTime").html(y + "年" + (m > 9 ? m : ("0" + m)) + "月" + (d > 9 ? d : ("0" + d)) + "日 " + (h > 9 ? h : ("0" + h)) + ":" + (i > 9 ? i : ("0" + i)) + ":" + (s > 9 ? s : ("0" + s)));
}

/**
 * 检查是否第一次登陆
 */
function checkLogin() {
    var isFirstLogin = $("#isFirstLogin").val();
    if (1 == isFirstLogin) {
        //错误提示信息的方法
        $.messager.alert('系统提示', '尊敬的用户,您的初始密码还未修改,请先修改您的密码!', 'info', function () {
                setTimeout('dialogPassword(false);', 100);
            }
        );
    }
}

/**
 * 显示用户密码修改弹出窗口
 */
function dialogPassword(val) {
    $('#reseUserPassword').dialog({
        title: "用户密码修改",
        width: 600,
        height: 300,
        modal: true,//设置遮罩层
        closable: val,//不显示关闭按钮
        closed: false,
        cache: false,
        collapsible: true,//折叠按钮
        left: 200,
        top: 100,
        /*minimizable:true,*/ //最小化按钮
        // maximizable: true,//最大化按钮
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function () {
                subPassword();//修改密码
            }
        }]

    });
}

/**
 * 修改密码的js
 */
function subPassword() {
    if (!$("#pwdform").form('validate')) {
        return;
    }
    $.messager.confirm('系统提示', '确定保存密码信息吗？', function (param) {
        if (!param) {
            return;
        }
        $.messager.progress({text: "正在提交数据中..."});
        $.ajax({
                type: "post",
                url: system + "/userinfo/updateUserPassword",
                data: {
                    oldPassword: new SM3().sm3encrypt($.trim($("#oldPassword").val())),
                    newPassword: new SM3().sm3encrypt($.trim($("#newPassword").val())),
                    affirmPassword: new SM3().sm3encrypt($.trim($("#affirmPassword").val()))
                },
                dataType: "JSON",
                success: function (data) {
                    $.messager.progress('close');
                    if (successcode != data.code) {
                        return errorHandle(data);
                    }
                    //错误提示信息的方法
                    $.messager.alert('系统提示', data.message, 'info', function () {
                            setTimeout('logout();', 100);
                        }
                    );
                }, error: function (data) {
                    $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
                    $.messager.progress('close');
                }
            }
        );
    });
}

function logout() {
    window.location.href = system + "/userlogin/logout";
}

/**
 * 加载公告
 */
function addNotice() {
    // 弹出公告框
    var dialogWidth = 300;		// dialog的宽度
    var dialogHeight = 150;		// dialog的高度
    var topPosition = $(window).height() - dialogHeight;
    var leftPosition = $(window).width() - dialogWidth;
    $('#dlgNotic').dialog({
        title: "公告信息",
        width: dialogWidth,
        height: dialogHeight,
        top: topPosition,
        left: leftPosition,
        modal: false,//设置遮罩层
        closable: true,//不显示关闭按钮
        closed: false,
        cache: false,
        collapsible: false,//折叠按钮
        minimizable: false,  //最小化按钮
        maximizable: false,//最大化按钮
    });
}

/**
 * 初始化加载数据
 */
function initData() {
    $.ajax({
            type: "post",
            url: system + "/main/initData",
            data: {},
            dataType: "JSON",
            success: function (data) {
                if (successcode != data.code) {
                    return errorHandle(data);
                }
                var notice = data.data.notice;
                if (!isNull(notice)) {
                    $("#dlgNotic").html(notice);
                    addNotice();//加载公告
                    // 10秒中关闭公告
                    window.setTimeout(" $('#dlgNotic').dialog('close')", 10000);
                }
                var version = data.data.version;
                if (!isNull(version)) {
                    $("#version").text("版本号:" + version);
                }
                var footerMsg = data.data.footerMsg;
                if (!isNull(footerMsg)) {
                    $("#footerMsg").html(footerMsg);
                }
                var sqlScript = data.data.sql_script;
                if (!isNull(sqlScript)) {
                    getChartSqlScript(sqlScript);
                }
                var reportWroldTable = data.data.report_wrold_table;
                if (!isNull(reportWroldTable)) {
                    getChartReportWroldTable(reportWroldTable);
                }
                var reportWroldSql = data.data.report_wrold_sql;
                if (!isNull(reportWroldSql)) {
                    getChartReportWroldSql(reportWroldSql);
                }
            }, error: function (data) {
                $.messager.alert('系统提示', "系统异常，请稍后重试！", 'error');
            }
        }
    );
}

/**
 * 加载提交的脚本统计图
 */
function getChartSqlScript(sqlScript) {
    setChartLang();
    Highcharts.chart('containerSqlScript', {
        chart: {
            type: 'column'   //柱状图
            //  type: 'line'   //折现图
            //type: 'pie'   //饼图
        },
        title: {
            text: '版本脚本统计图'
        }/*,
        subtitle: {
            text: '数据来源: WorldClimate.com'
        }*/,
        exporting: {
            enabled: true //用来设置是否显示‘打印’,'导出'等功能按钮，不设置时默认为显示
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        xAxis: {
            categories: sqlScript.categories/*["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]*/,
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: '数量 '
            }
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                borderWidth: 0
            }
        },
        series: sqlScript.series
    });
}

/**
 * 表结构统计图
 */
function getChartReportWroldTable(reportWroldTable) {
    setChartLang();
    Highcharts.chart('containerWroldTable', {
        chart: {
            //type: 'column'   //柱状图
            type: 'line'   //折现图
            //type: 'pie'   //饼图
        },
        title: {
            text: '版本表结构统计图'
        }/*,
        subtitle: {
            text: '数据来源: WorldClimate.com'
        }*/,
        exporting: {
            enabled: true //用来设置是否显示‘打印’,'导出'等功能按钮，不设置时默认为显示
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        xAxis: {
            categories: reportWroldTable.categories/*["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]*/,
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: '数量 '
            }
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                borderWidth: 0
            }
        },
        series: reportWroldTable.series
    });
}

/**
 * 脚本统计图
 */
function getChartReportWroldSql(sql_script) {
    setChartLang();
    Highcharts.chart('containerDataSql', {
        chart: {
            //type: 'column'   //柱状图
            type: 'line'   //折现图
            //type: 'pie'   //饼图
        },
        title: {
            text: '版本脚本统计图'
        }/*,
        subtitle: {
            text: '数据来源: WorldClimate.com'
        }*/,
        exporting: {
            enabled: true //用来设置是否显示‘打印’,'导出'等功能按钮，不设置时默认为显示
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        xAxis: {
            categories: sql_script.categories/*["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]*/,
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: '数量 '
            }
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                borderWidth: 0
            }
        },
        series: sql_script.series
    });
}

/**
 * 加载提交的脚本统计图
 */
function getChart(sql_script) {
    setChartLang();
    Highcharts.chart('containerSqlScript', {
        chart: {
            //  type: 'column'   //柱状图
            type: 'line'   //折现图
            //type: 'pie'   //饼图
        },
        title: {
            text: '版本脚本统计图'
        },
        exporting: {
            enabled: true //用来设置是否显示‘打印’,'导出'等功能按钮，不设置时默认为显示
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        xAxis: {
            categories: sql_script.categories,
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: '数量 '
            }
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y} </b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                borderWidth: 0
            }
        },
        series: sql_script.series
    });
}


function getChart2() {
    setChartLang();
    Highcharts.chart('container2', {
        title: {
            text: '浏览器占比',
            align: 'center',
            verticalAlign: 'middle',
            y: 100
        },
        tooltip: {
            headerFormat: '{series.name}<br>',
            pointFormat: '{point.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                dataLabels: {
                    enabled: true,
                    distance: -50,
                    style: {
                        fontWeight: 'bold',
                        color: 'white',
                        textShadow: '0px 1px 2px black'
                    }
                },
                startAngle: -90, // 圆环的开始角度
                endAngle: 90,    // 圆环的结束角度
                center: ['50%', '75%']
            }
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        series: [{
            type: 'pie',
            name: '浏览器占比',
            innerSize: '50%',
            data: [
                ['Firefox', 45.0],
                ['IE', 26.8],
                ['Chrome', 12.8],
                ['Safari', 8.5],
                ['Opera', 6.2],
                ['其他', 0.7]
                /*  {
                      name: '其他',
                      y: 0.7,
                      dataLabels: {
                          // 数据比较少，没有空间显示数据标签，所以将其关闭
                          enabled: false
                      }
                  }*/
            ]
        }]
    });
}

function getChart3() {
    setChartLang();
    Highcharts.chart('container3', {

        title: {
            text: 'Solar Employment Growth by Sector, 2014-2020'
        },

        subtitle: {
            text: 'Source: thesolarfoundation.com'
        },

        yAxis: {
            title: {
                text: 'Number of Employees'
            }
        },
        credits: {
            enabled: false     //不显示LOGO
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },

        plotOptions: {
            series: {
                label: {
                    connectorAllowed: false
                },
                pointStart: 2014
            }
        },

        series: [{
            name: 'Installation',
            data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
        }, {
            name: 'Manufacturing',
            data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
        }, {
            name: 'Sales & Distribution',
            data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
        }, {
            name: 'Project Development',
            data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
        }, {
            name: 'Other',
            data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
        }],

        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }

    });
}
